package com.yimi.appstore.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yimi.appstore.R;
import com.yimi.appstore.YimiApplication;
import com.yimi.appstore.adapter.DownloadExpandAdapter;
import com.yimi.appstore.adapter.DownloadJobAdapter;
import com.yimi.appstore.adapter.MyAdapter;
import com.yimi.appstore.adapter.MyViewPager;
import com.yimi.appstore.adapter.SpecialAdapter;
import com.yimi.appstore.download2.DownloadEntity;
import com.yimi.appstore.download2.DownloadJob;
import com.yimi.appstore.download2.DownloadManager;
import com.yimi.appstore.download2.FileService;
import com.yimi.appstore.fileexplorer.FileCategoryHelper.FileCategory;
import com.yimi.appstore.service.Page;
import com.yimi.appstore.service.WlanService;
import com.yimi.appstore.util.BitmapUtil;
import com.yimi.appstore.util.FileUtils;
import com.yimi.appstore.util.FileUtils.SDCardInfo;
import com.yimi.appstore.util.GlobalConsts;
import com.yimi.appstore.view.CategoryBar;
import com.yimi.appstore.view.MyViewFlow;
import com.yimi.appstore.view.SyncHorizontalScrollView;

/**
 * 首页
 * 
 * @author Tank
 * 
 */
public class MainActivity2 extends Activity {

	private static final String TAG = "MainActivity";
	private static final int KEY_RESOURCE = 0;
	private static final int KEY_MANAGEMENT = 1;
	private static final int KEY_SPECIAL = 2;
	private static final int KEY_DOWNLOAD = 3;
	private static final int KEY_SPECIAL_APP = 21;
	private static final int KEY_SPECIAL_MUSIC = 22;
	private static final int KEY_SPECIAL_VIDEO = 23;
	private static final int KEY_SPECIAL_TEXT = 24;
	private boolean isResourceLoading, isManagementLoading, isSpecialLoading, isDownLoading;
	private Context mContext;
	private SyncHorizontalScrollView shsView;
	private RelativeLayout rl_scroll;
	private RadioGroup tab_content;
	private View cursor;
	private ViewPager awesomePager;
	private List<RadioButton> rb_pages = new ArrayList<RadioButton>();
	private int mCurrentCheckedRadioLeft;// 当前的Tab距离左侧的距离
	private List<View> listViews;
	private LayoutInflater mInflater;
	private int cursorWidth;// 宽度
	private List<String> channels = new ArrayList<String>();
	private ListView mRecommendApplv, mMusicSpelv, mVediolv, mTextlv;
	private MyAdapter mRecommendAppadapter, mAppSpeAdapter, mMusicSpeAdapter, mVedioSpeAdapter, mTextSpeAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mContext = this;
		initUI();
		startService(new Intent(mContext, WlanService.class));
		FileService fileService = new FileService(this);
		YimiApplication.jobList = fileService.getAllDownload(this); // 初始化下载记录
		YimiApplication.downloadHistoryList = fileService.getAllDownloadHistory();
	}

	private void initUI() {
		mInflater = getLayoutInflater();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		cursorWidth = dm.widthPixels / 4;
		shsView = (SyncHorizontalScrollView) findViewById(R.id.mhsv);
		rl_scroll = (RelativeLayout) findViewById(R.id.rl_scroll);
		tab_content = (RadioGroup) findViewById(R.id.tab_content);
		cursor = findViewById(R.id.cursor);
		LayoutParams cursor_Params = cursor.getLayoutParams();
		cursor_Params.width = cursorWidth;// 初始化滑动下标的宽
		cursor.setLayoutParams(cursor_Params);
		shsView.setSomeParam(rl_scroll, this);
		initTabContent();
		initTabValue();
		creatViewPager();

	}

	// 初始化Tabcontent
	private void initTabContent() {
		channels.add("资源");
		channels.add("管理");
		channels.add("专题");
		channels.add("下载");
		for (int i = 0; i < channels.size(); i++) {
			RadioButton radioButton = (RadioButton) mInflater.inflate(R.layout.tab_group_item, null);
			radioButton.setId(i);
			radioButton.setText(channels.get(i));
			radioButton.setLayoutParams(new LayoutParams(cursorWidth, LayoutParams.FILL_PARENT));
			if (i == 0)
				radioButton.setChecked(true);
			rb_pages.add(radioButton);
		}
	}

	private void initTabValue() {
		tab_content.removeAllViews();
		for (int i = 0; i < channels.size(); i++) {
			rb_pages.get(i).setText(channels.get(i));
			tab_content.addView(rb_pages.get(i));
		}
		tab_content.setOnCheckedChangeListener(top_tab_onCheckedChangeListener);
	}

	/**
	 * 初始化ViewPager
	 */
	private void creatViewPager() {
		if (listViews == null) {
			listViews = new ArrayList<View>();
			listViews.add(initResourcePage());
			listViews.add(initManagementPage());
			listViews.add(initSpecialPage());
			listViews.add(initDownloadPage());
		}
		awesomePager = new MyViewPager(mContext, R.id.vPager, listViews).getAwesomePager();
		awesomePager.setOnPageChangeListener(new MyOnPageChangeListener());
		awesomePager.setCurrentItem(0);
	}

	/**
	 * 页卡切换监听
	 * 
	 * @author Tank
	 * 
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			if (rb_pages != null && rb_pages.size() > position) {
				((RadioButton) rb_pages.get(position)).performClick();
			}
			switch (position) {
			case 0:
				if (!isResourceLoading)
					getData(KEY_RESOURCE, mAppSpelv, mAppSpeAdapter, mRerrorTv, mRpb, mRrefreshBtn, new Page(),
							mRLoadingV);
				break;
			case 1:
				break;
			case 2:
				if (!isSpecialLoading) {
					getData(KEY_SPECIAL_APP, mAppSpelv, mAppSpeAdapter, mSapperrorTv, mSapppb, mSapprefreshBtn,
							new Page(), mSappLoadingV);
//					getADData(KEY_SPECIAL_APP, mSapppb);
				}
				break;
			case 3:
				updataDownloadListView();
				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	/**
	 * 顶部RadioGroup点击CheckedChanged监听
	 */
	private OnCheckedChangeListener top_tab_onCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			try {
				if (tab_content != null && tab_content.getChildCount() > 0 && tab_content.getChildAt(checkedId) != null) {
					TranslateAnimation _TranslateAnimation = new TranslateAnimation(mCurrentCheckedRadioLeft,
							((RadioButton) tab_content.getChildAt(checkedId)).getLeft(), 0f, 0f);
					// 匀速
					_TranslateAnimation.setInterpolator(new LinearInterpolator());
					_TranslateAnimation.setDuration(100);
					// 动画执行后，控件将停留在动画结束的状态
					_TranslateAnimation.setFillAfter(true);
					cursor.startAnimation(_TranslateAnimation);
					awesomePager.setCurrentItem(checkedId);// 让下方ViewPager跟随上面的HorizontalScrollView切换
					mCurrentCheckedRadioLeft = ((RadioButton) tab_content.getChildAt(checkedId)).getLeft();
					shsView.smoothScrollTo((checkedId > 1 ? ((RadioButton) tab_content.getChildAt(checkedId)).getLeft()
							: 0) - ((RadioButton) tab_content.getChildAt(2)).getLeft(), 0);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	};

	View appHeadView = null;
	View mRLoadingV;
	TextView mRerrorTv;
	Button mRrefreshBtn;
	ProgressBar mRpb;
	ImageView appIv, musicIv, videoIv, textIv;
	RelativeLayout rl;
	WebView webView;

	/**
	 * 初始化资源页
	 */
	private View initResourcePage() {
		View Rpage = mInflater.inflate(R.layout.activity_webview_layout, null);
		webView = (WebView) Rpage.findViewById(R.id.webview);
		webView.requestFocus();
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);

		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

		});

		webView.addJavascriptInterface(this, "android");
//		webView.loadUrl("file:///android_asset/index/index.html");
		webView.loadUrl("http://192.168.0.36:8080/yms/pages/index.jsp");
		return Rpage;
	}


	public void download(String appName, String url) {
		Log.d(TAG, "invoke download() >> url:" + url + ",appName:" + appName);
		downloadManager.addDownloadTask(url, appName, "" ,GlobalConsts.MEDIA_MUSIC);
	}

	private OnClickListener resourceOncClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			awesomePager.setCurrentItem(2, true);
			switch (v.getId()) {
			case R.id.app_category:
				rbApp.setChecked(true);
				break;
			case R.id.music_category:
				rbMusic.setChecked(true);
				break;
			case R.id.video_category:
				rbVideo.setChecked(true);
				break;
			case R.id.book_category:
				rbText.setChecked(true);
				break;
			}
		}
	};

	/**
	 * 初始化管理页
	 */
	private CategoryBar mCategoryBar;
	private LinearLayout appLy, mnpLy, videoLy, textLy;
	private TextView appCountstv, mnpCountstv, videoCountstv, textCountstv;

	private View initManagementPage() {
		View Mpage = mInflater.inflate(R.layout.management_layout, null);
		appLy = (LinearLayout) Mpage.findViewById(R.id.category_apps);
		mnpLy = (LinearLayout) Mpage.findViewById(R.id.category_music_pic);
		videoLy = (LinearLayout) Mpage.findViewById(R.id.category_video);
		textLy = (LinearLayout) Mpage.findViewById(R.id.category_text);
		appLy.setOnClickListener(new managementOnclickListener());
		mnpLy.setOnClickListener(new managementOnclickListener());
		videoLy.setOnClickListener(new managementOnclickListener());
		textLy.setOnClickListener(new managementOnclickListener());

		mCategoryBar = (CategoryBar) Mpage.findViewById(R.id.category_bar);
		mCategoryBar.addCategory(R.drawable.category_bar_apk);
		SDCardInfo sdCardInfo = FileUtils.getSDCardInfo();
		if (sdCardInfo != null) {
			mCategoryBar.setFullValue(sdCardInfo.total);
			setTextView(R.id.sd_card_capacity,
					getString(R.string.sd_card_size, FileUtils.convertStorage(sdCardInfo.total)), Mpage);
			setTextView(R.id.sd_card_available,
					getString(R.string.sd_card_available, FileUtils.convertStorage(sdCardInfo.free)), Mpage);
			setTextView(R.id.sd_card_used,
					getString(R.string.sd_card_used, FileUtils.convertStorage(sdCardInfo.total - sdCardInfo.free)),
					Mpage);
			mCategoryBar.setCategoryValue(0, sdCardInfo.total - sdCardInfo.free);
		}
		if (mCategoryBar.getVisibility() == View.VISIBLE) {
			mCategoryBar.startAnimation();
		}
		return Mpage;
	}

	private class managementOnclickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.category_apps:
				Toast.makeText(mContext, "app", Toast.LENGTH_SHORT).show();
				ApkExplorerActivity.lanuchActivity(mContext);
				break;

			case R.id.category_music_pic:
				Toast.makeText(mContext, "music", Toast.LENGTH_SHORT).show();
				CategoryFileActivity.lanuchActivity(mContext, FileCategory.Music);
				break;

			case R.id.category_video:
				Toast.makeText(mContext, "video", Toast.LENGTH_SHORT).show();
				CategoryFileActivity.lanuchActivity(mContext, FileCategory.Video);
				break;
			case R.id.category_text:
				CategoryFileActivity.lanuchActivity(mContext, FileCategory.Picture);
				Toast.makeText(mContext, "text", Toast.LENGTH_SHORT).show();
				break;
			}

		}

	}

	/**
	 * 初始化专题页
	 */
	View Spage;
	View specialAppHeadView;
	List<HashMap<String, Object>> list;
	View mSappLoadingV;
	TextView mSapperrorTv;
	Button mSapprefreshBtn;
	ProgressBar mSapppb;
	RadioGroup bottom_tab_content;
	RadioButton rbApp, rbMusic, rbVideo, rbText;
	ListView mAppSpelv;
	private String ICON;
	private String SINGER_PIC;
	private String ICON_URL;
	private List<HashMap<String, Object>> appList, musicList, videoList, textList, appAdList, musicAdList, videoAdList,
			textAdList;

	private View initSpecialPage() {
		 Spage = mInflater.inflate(R.layout.special_layout, null);
		 bottom_tab_content = (RadioGroup)
		 Spage.findViewById(R.id.special_category);
		 rbApp = (RadioButton) bottom_tab_content.findViewById(R.id.app_rb);
		 rbMusic = (RadioButton)
		 bottom_tab_content.findViewById(R.id.music_rb);
		 rbVideo = (RadioButton)
		 bottom_tab_content.findViewById(R.id.video_rb);
		 rbText = (RadioButton) bottom_tab_content.findViewById(R.id.text_rb);
		 bottom_tab_content.setOnCheckedChangeListener(bottom_tab_OnCheckedChangeListener);
		
		 mSappLoadingV = Spage.findViewById(R.id.loading_ly);
		 mSapperrorTv = (TextView) Spage.findViewById(R.id.tv_error);
		 mSapprefreshBtn = (Button) Spage.findViewById(R.id.retry);
		 mSapppb = (ProgressBar) Spage.findViewById(R.id.progress_bar);
		 specialAppHeadView = mInflater.inflate(R.layout.special_head_view,
		 null);
		 mAppSpelv = (ListView) Spage.findViewById(R.id.recomend_lv);
		 mAppSpeAdapter = new SpecialAdapter(mContext, new
		 ArrayList<HashMap<String, Object>>());
		 mAppSpelv.addHeaderView(specialAppHeadView);
		 mAppSpelv.setAdapter(mAppSpeAdapter);
//		Spage = mInflater.inflate(R.layout.special_layout, null);
//		webView = (WebView) Spage.findViewById(R.id.webview);
//		webView.requestFocus();
//		WebSettings settings = webView.getSettings();
//		settings.setJavaScriptEnabled(true);
//
//		webView.setWebViewClient(new WebViewClient() {
//
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				view.loadUrl(url);
//				return true;
//			}
//
//		});
//
//		webView.addJavascriptInterface(this, "yimi");
//
//		webView.loadUrl("file:///android_asset/theme/theme.html");
		return Spage;
	}

	private OnCheckedChangeListener bottom_tab_OnCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.app_rb:
				if (appList == null || appAdList == null) {
					mSapppb.setVisibility(View.VISIBLE);
					getData(KEY_SPECIAL_APP, mAppSpelv, mAppSpeAdapter, mSapperrorTv, mSapppb, mSapprefreshBtn,
							new Page(), mSappLoadingV);
					getADData(KEY_SPECIAL_APP, mSapppb);
				} else {
					mAppSpeAdapter.updateListData(appList);
					Listener l = new Listener(appAdList);
					vf.creatMyViewFlow(appAdList, l, awesomePager);
				}

				Toast.makeText(mContext, "应用", Toast.LENGTH_SHORT).show();
				break;

			case R.id.music_rb:
				if (musicList == null || musicAdList == null) {
					mSapppb.setVisibility(View.VISIBLE);
					getData(KEY_SPECIAL_MUSIC, mAppSpelv, mAppSpeAdapter, mSapperrorTv, mSapppb, mSapprefreshBtn,
							new Page(), mSappLoadingV);
					getADData(KEY_SPECIAL_MUSIC, mSapppb);
				} else {
					mAppSpeAdapter.updateListData(musicList);
					Listener l = new Listener(musicAdList);
					vf.creatMyViewFlow(musicAdList, l, awesomePager);
				}
				Toast.makeText(mContext, "音乐", Toast.LENGTH_SHORT).show();
				break;
			case R.id.video_rb:
				if (videoList == null || videoAdList == null) {
					mSapppb.setVisibility(View.VISIBLE);
					getData(KEY_SPECIAL_VIDEO, mAppSpelv, mAppSpeAdapter, mSapperrorTv, mSapppb, mSapprefreshBtn,
							new Page(), mSappLoadingV);
					getADData(KEY_SPECIAL_VIDEO, mSapppb);
				} else {
					mAppSpeAdapter.updateListData(videoList);
					Listener l = new Listener(videoAdList);
					vf.creatMyViewFlow(videoAdList, l, awesomePager);
				}
				Toast.makeText(mContext, "视频", Toast.LENGTH_SHORT).show();
				break;
			case R.id.text_rb:
				if (textList == null || textAdList == null) {
					mSapppb.setVisibility(View.VISIBLE);
					getData(KEY_SPECIAL_TEXT, mAppSpelv, mAppSpeAdapter, mSapperrorTv, mSapppb, mSapprefreshBtn,
							new Page(), mSappLoadingV);
					getADData(KEY_SPECIAL_TEXT, mSapppb);
				} else {
					mAppSpeAdapter.updateListData(textList);
					Listener l = new Listener(textAdList);
					vf.creatMyViewFlow(textAdList, l, awesomePager);
				}
				Toast.makeText(mContext, "小说", Toast.LENGTH_SHORT).show();
				break;
			}

		}
	};

	/**
	 * 初始化下载页
	 */
	ImageView iv;
	private DownloadManager downloadManager;
	private ExpandableListView downloadListView,downloadHistoryListView;
	private DownloadJobAdapter downloadJobAdapter;
	private DownloadExpandAdapter downloadExpandAdapter;
	private View downloadingTips,downloadHistoryTips;
	private View initDownloadPage() {
		View v = mInflater.inflate(R.layout.download_layout, null);
		downloadListView = (ExpandableListView) v.findViewById(R.id.download_list);
		downloadListView.setGroupIndicator(null);
		downloadJobAdapter = new DownloadJobAdapter(mContext, new ArrayList<DownloadJob>());
		downloadListView.setAdapter(downloadJobAdapter);
		downloadManager = DownloadManager.getInstance(mContext);
		downloadManager.setDownloadJobAdapter(downloadJobAdapter);
		downloadManager.setMainHanlder(mHandler);
		
		
		downloadHistoryListView = (ExpandableListView) v.findViewById(R.id.app_download_history_list);
		downloadHistoryListView.setGroupIndicator(null);
		downloadExpandAdapter = new DownloadExpandAdapter(mContext, new ArrayList<DownloadEntity>());
		downloadHistoryListView.setAdapter(downloadExpandAdapter);
		downloadingTips = v.findViewById(R.id.download_ing_tips);
		downloadHistoryTips = v.findViewById(R.id.download_history_tips);
		return v;
	}

	public void updataDownloadListView() {
		if(!YimiApplication.jobList.isEmpty()){
			downloadingTips.setVisibility(View.VISIBLE);
			downloadListView.setVisibility(View.VISIBLE);
			downloadJobAdapter.updateListData(YimiApplication.jobList);
		} else {
			downloadingTips.setVisibility(View.GONE);
			downloadListView.setVisibility(View.GONE);
		}
		if(!YimiApplication.downloadHistoryList.isEmpty()){
			downloadHistoryTips.setVisibility(View.VISIBLE);
			downloadHistoryListView.setVisibility(View.VISIBLE);
			downloadExpandAdapter.updateListData(YimiApplication.downloadHistoryList);
		} else {
			downloadHistoryTips.setVisibility(View.GONE);
			downloadHistoryListView.setVisibility(View.GONE);
		}
	}
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				updataDownloadListView();
				break;

			default:
				break;
			}
		}
		
	};

	/**
	 * 获取广告栏数据
	 */
	MyViewFlow vf;

	private void getADData(final int type, final ProgressBar mSapppb) {
		if (mSapppb.getVisibility() == View.VISIBLE)
			new AsyncTask<Void, Void, List<HashMap<String, Object>>>() {

				@Override
				protected void onPreExecute() {
					vf = new MyViewFlow(mContext, Spage, R.id.viewflow, R.id.viewflowindic);
					List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
					for (int i = 0; i < 4; i++) {
						HashMap<String, Object> item = new HashMap<String, Object>();
						item.put("image", BitmapFactory.decodeResource(getResources(), R.drawable.h1));
						list.add(item);
					}
					vf.creatMyViewFlow(list, null, awesomePager);
				}

				@Override
				protected List<HashMap<String, Object>> doInBackground(Void... params) {
					List<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
					switch (type) {
					case KEY_SPECIAL_APP:
						for (int i = 0; i < 4; i++) {
							HashMap<String, Object> item = new HashMap<String, Object>();
							item.put("image", BitmapFactory.decodeResource(getResources(), R.drawable.h2));
							result.add(item);
						}
						appAdList = result;
						break;

					case KEY_SPECIAL_MUSIC:
						for (int i = 0; i < 4; i++) {
							HashMap<String, Object> item = new HashMap<String, Object>();
							item.put("image", BitmapFactory.decodeResource(getResources(), R.drawable.h3));
							result.add(item);
						}
						musicAdList = result;
						break;

					case KEY_SPECIAL_VIDEO:
						for (int i = 0; i < 4; i++) {
							HashMap<String, Object> item = new HashMap<String, Object>();
							item.put("image", BitmapFactory.decodeResource(getResources(), R.drawable.h4));
							result.add(item);
						}
						videoAdList = result;
						break;
					case KEY_SPECIAL_TEXT:
						for (int i = 0; i < 4; i++) {
							HashMap<String, Object> item = new HashMap<String, Object>();
							item.put("image", BitmapFactory.decodeResource(getResources(), R.drawable.h5));
							result.add(item);
						}
						textAdList = result;
						break;
					}

					Log.i(TAG, "list=" + result);
					/*
					 * for (HashMap<String, Object> item : result) { String
					 * strUrl = item.get("imageUrl").toString(); Bitmap bitmap =
					 * null; for (int i = 0; i < 5; i++) { bitmap =
					 * BitmapUtil.getHttpBitmap(strUrl); if (bitmap != null) {
					 * break; } } item.put("image", bitmap); }
					 */
					return result;
				}

				@Override
				protected void onPostExecute(List<HashMap<String, Object>> result) {
					if (result != null && !result.isEmpty()) {
						Listener l = new Listener(result);
						Log.i(TAG, "更新：" + result);
						vf.creatMyViewFlow(result, l, awesomePager);
					}
				};
			}.execute();
	}

	/**
	 * 显示广告栏
	 * 
	 * @param bitmaps
	 */
	private void showViewFlow(List<HashMap<String, Object>> list, View parent, ViewPager awesomePager) {
		MyViewFlow vf = new MyViewFlow(mContext, parent, R.id.viewflow, R.id.viewflowindic);
		Listener l = new Listener(list);
		vf.creatMyViewFlow(list, l, awesomePager);
	}

	/**
	 * @author Administrator 广告栏点击OnClickListener
	 */
	class Listener implements OnClickListener {
		List<HashMap<String, Object>> list;

		public Listener(List<HashMap<String, Object>> list) {
			this.list = list;
		}

		@Override
		public void onClick(View v) {
			int position = (Integer) v.getTag();
			Toast.makeText(mContext, "ad:" + position, Toast.LENGTH_SHORT);
		}

	}

	private void setTextView(int id, String t, View mRootView) {
		TextView text = (TextView) mRootView.findViewById(id);
		text.setText(t);
	}

	private void getData(final int id, final ListView listView, final MyAdapter myAdapter, final TextView tvError,
			final ProgressBar progressBar, final Button retryBtn, final Page page, final View loadingView) {/*
		if (progressBar.getVisibility() == View.VISIBLE || tvError.getVisibility() == View.VISIBLE) {
			new AsyncTask<Void, Void, List<HashMap<String, Object>>>() {
				@Override
				protected void onPreExecute() {
					// 加载数据时，先销毁掉异步加载图片任务。
					BitmapUtil.destroyedAsyncTask();
					loadingView.setVisibility(View.VISIBLE);
					retryBtn.setVisibility(View.GONE);
					tvError.setText("正在加载……");
					progressBar.setVisibility(View.VISIBLE);
				};

				@Override
				protected List<HashMap<String, Object>> doInBackground(Void... params) {
					List<HashMap<String, Object>> result = null;
					switch (id) {
					case KEY_RESOURCE:
						// 防止加载服务器数据还没有完成时，可能出现数据重复加载
						if (!isResourceLoading) {
							isResourceLoading = true;
							result = new ArrayList<HashMap<String, Object>>();
							for (int i = 0; i < 10; i++) {
								HashMap<String, Object> map = new HashMap<String, Object>();
								result.add(map);
							}
							isResourceLoading = false;
						}
						break;
					case KEY_SPECIAL:
						if (!isSpecialLoading) {
							isSpecialLoading = true;
							result = new ArrayList<HashMap<String, Object>>();
							for (int i = 0; i < 10; i++) {
								HashMap<String, Object> map = new HashMap<String, Object>();
								result.add(map);
							}
							isSpecialLoading = false;
						}
						break;
					case KEY_MANAGEMENT:
						if (!isManagementLoading) {
							isManagementLoading = true;

							isManagementLoading = false;
						}
						break;

					case KEY_DOWNLOAD:

						break;

					case KEY_SPECIAL_APP:
						result = new ArrayList<HashMap<String, Object>>();
						for (int i = 0; i < 5; i++) {
							HashMap<String, Object> map = new HashMap<String, Object>();
							result.add(map);
						}
						appList = result;
						break;
					case KEY_SPECIAL_MUSIC:
						result = new ArrayList<HashMap<String, Object>>();
						for (int i = 0; i < 6; i++) {
							HashMap<String, Object> map = new HashMap<String, Object>();
							result.add(map);
						}
						musicList = result;
						break;
					case KEY_SPECIAL_VIDEO:
						result = new ArrayList<HashMap<String, Object>>();
						for (int i = 0; i < 7; i++) {
							HashMap<String, Object> map = new HashMap<String, Object>();
							result.add(map);
						}
						videoList = result;
						break;
					case KEY_SPECIAL_TEXT:
						result = new ArrayList<HashMap<String, Object>>();
						for (int i = 0; i < 8; i++) {
							HashMap<String, Object> map = new HashMap<String, Object>();
							result.add(map);
						}
						textList = result;
						break;
					}

					Log.i(TAG, "getData result=" + result);
					return result;
				}

				protected void onPostExecute(java.util.List<java.util.HashMap<String, Object>> result) {
					progressBar.setVisibility(View.GONE);
					if (result != null && !result.isEmpty()) {
						loadingView.setVisibility(View.GONE);
						retryBtn.setVisibility(View.GONE);
						tvError.setVisibility(View.GONE);
						listView.setVisibility(View.VISIBLE);
						myAdapter.updateListData(result);
						listView.setAdapter(myAdapter);
						// 异步加载图片任务
						// updateBitmap(id);
					} else {
						retryBtn.setVisibility(View.VISIBLE);
						retryBtn.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								getData(id, listView, myAdapter, tvError, progressBar, retryBtn, page, loadingView);
							}
						});
						tvError.setText("加载数据失败，请重试");
						tvError.setVisibility(View.VISIBLE);
					}
				};
			}.execute();

		}

	*/}

	/**
	 * 根据适配器数据中的图标地址，从服务器中获取图标图片，并将其显示出来
	 * 
	 * @param id
	 */
	private void updateBitmap(int id) {
		switch (id) {
		case KEY_RESOURCE:
			BitmapUtil.updateAdapterBitmap(mRecommendApplv, mRecommendAppadapter, SINGER_PIC, ICON);
			break;
		case KEY_SPECIAL:
			BitmapUtil.updateAdapterBitmap(mAppSpelv, mAppSpeAdapter, ICON_URL, ICON);
			break;

		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		isDownLoading = false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode && webView.canGoBack()) {
			webView.goBack();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private static Boolean isExit = false;
	Handler exitHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}
	};

	/**
	 * 连续点击两次返回退出
	 */
	protected void exit() {
		if (isExit == false) {
			isExit = true;
			Toast.makeText(this, "再按一次返回将退出一米!", Toast.LENGTH_SHORT).show();
			exitHandler.sendEmptyMessageDelayed(0, 2000);
		} else {
			// 暂停所有正在下载的任务
			for (int i = 0; i < YimiApplication.jobList.size(); i++) {
				if (YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_FINISH
						&& YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_INSTALLED)
					YimiApplication.jobList.get(i).setJobStatus(DownloadManager.STATE_PAUSE);
			}
			for (int i = 0; i < YimiApplication.jobList.size(); i++) {
				if (YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_FINISH
						&& YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_INSTALLED)
					Log.d(TAG, "pauseDownloadTask>>" + i);
				downloadManager.pauseDownloadTask(i);
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finish();
			System.exit(0);
		}
	}
}